<?php
class web extends Action {
	function initAction() {
	}
	
	public function initucAction() 
	{ 
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		//echo $_COOKIE['Example_auth'];
		//print_r($_COOKIE);
		/**
		 * 获取当前用户的 UID 和 用户名
		 * Cookie 解密直接用 uc_authcode 函数，用户使用自己的函数
		 */
		if(!empty($_COOKIE['Example_auth'])) {
			list($Example_uid, $Example_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
		} else {
			$Example_uid = $Example_username = '';
		}
		if(!$Example_username) {
			//用户未登录
			echo '<a href="/qsf_mvc/my/web/login/">登录</a> ';
			echo '<a href="/qsf_mvc/my/web/register/">注册</a> ';
		} else {
			//用户已登录
			echo '<script src="/qsf_mvc/app/views/js/ucexample.js"></script><div id="append_parent"></div>';
			echo $Example_username.' <a href="/qsf_mvc/my/web/logout/">退出</a> ';
			echo ' <a href="/qsf_mvc/my/web/pmlist/">短消息列表</a> ';
			echo $newpm ? '<font color="red">New!('.$newpm.')</font> ' : NULL;
			echo '<a href="###" onclick="pmwin(\'open\')">进入短消息中心</a> ';
			echo ' <a href="/qsf_mvc/my/web/friend/">好友</a> ';
			echo ' <a href="/qsf_mvc/my/web/avatar/">头像</a> ';
		}
		echo '<HR>';		
	}
	public function indexAction() 
	{ 
		$this->initucAction();
        $websiteObj = new website();
        $websitesRs = $websiteObj->getAll("`id` > 0");
        //print_r($websitesRs);
        $viewObj = new View();
        $viewObj->template_dir    = APP_PATH.'/views/'.$_GET['module'].'/';
        $viewObj->compile_dir     = APP_PATH.'/views_c/'.$_GET['module'].'/';
        $viewObj->cache_dir       = APP_PATH.'/cache/'.$_GET['module'].'/';
        $viewObj->caching = true;
        $viewObj->cache_lifetime = 3;
        $cacheid = $_GET['module'].'-'.$_GET['controller'].'-'.$_GET['action'].'-';
		if (!$viewObj->is_cached('view', $cacheid)) {
            $title = '个人书签';
            $viewObj->assign('title', $title)
                    ->assign('websitesRs', $websitesRs);     

       	}
        $viewObj->display('view',$cacheid);  
   

	}
	function addAction() {
		if (isset($_POST['submit'])) {
			$websiteObj = new website();
			$insertArr =  array(
					'url'    => $_POST['url'],
					'name'   => $_POST['name'],
					'addtime'=> time(),
			); 
			!empty($_POST['url']) && !empty($_POST['name']) && $affectedRows = $websiteObj->insert($insertArr);  
			//echo '添加成功记录数:'.$affectedRows;
			header('location:http://localhost/qsf_mvc/my/web/index/');
			//print_r($_POST);
		}else{
		    $viewObj = new View();
	        $viewObj->template_dir    = APP_PATH.'/views/'.$_GET['module'].'/';
	        $viewObj->compile_dir     = APP_PATH.'/views_c/'.$_GET['module'].'/';
	        $viewObj->cache_dir       = APP_PATH.'/cache/'.$_GET['module'].'/';
	        $viewObj->caching = false;
	        $viewObj->cache_lifetime = 0;
	        $viewObj->display('add');  	
		}

	}
	function loginAction() {	
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		if(empty($_POST['submit'])) {
			//登录表单
			echo '<form method="post" action="/qsf_mvc/my/web/login/">';
			echo '登录:';
			echo '<dl><dt>用户名</dt><dd><input name="username"></dd>';
			echo '<dt>密码</dt><dd><input name="password" type="password"></dd></dl>';
			echo '<input name="submit" type="submit"> ';
			echo '</form>';
		} else {
			//通过接口判断登录帐号的正确性，返回值为数组
			list($uid, $username, $password, $email) = uc_user_login($_POST['username'], $_POST['password']);
			//echo $uid.'-'.$username.'-'.$password.'-'.$email.'<BR>';
			//setcookie('Example_auth', '', -86400);//为了方便测试事先注销cookkie
			if($uid > 0) {
				setcookie('Example_auth', uc_authcode($uid."\t".$username, 'ENCODE'), time() + 86400, $cookiepath);
				//生成同步登录的代码
				$ucsynlogin = uc_user_synlogin($uid);
				echo '登录成功'.$ucsynlogin.'<br><a href="/qsf_mvc/my/web/index/">继续</a>';
			} elseif($uid == -1) {
				echo '用户不存在,或者被删除';
			} elseif($uid == -2) {
				echo '密码错';
			} else {
				echo '未定义';
			}
	 	}
	}
	
	function logoutAction() {
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		setcookie('Example_auth', '', -86400, $cookiepath);
		//生成同步退出的代码
		$ucsynlogout = uc_user_synlogout();
		echo '退出成功'.$ucsynlogout.'<br><a href="/qsf_mvc/my/web/index/">继续</a>';
	}
	
	function registerAction() {
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		if(empty($_POST['submit'])) {
			//注册表单
			echo '<form method="post" action="/qsf_mvc/my/web/register/">';
			echo '注册:';
			echo '<dl><dt>用户名</dt><dd><input name="username"></dd>';
			echo '<dt>密码</dt><dd><input name="password"></dd>';
			echo '<dt>Email</dt><dd><input name="email"></dd></dl>';
			echo '<input name="submit" type="submit">';
			echo '</form>';
		} else {
			//在UCenter注册用户信息
			$uid = uc_user_register($_POST['username'], $_POST['password'], $_POST['email']);
			if($uid <= 0) {
				if($uid == -1) {
					echo '用户名不合法';
				} elseif($uid == -2) {
					echo '包含要允许注册的词语';
				} elseif($uid == -3) {
					echo '用户名已经存在';
				} elseif($uid == -4) {
					echo 'Email 格式有误';
				} elseif($uid == -5) {
					echo 'Email 不允许注册';
				} elseif($uid == -6) {
					echo '该 Email 已经被注册';
				} else {
					echo '未定义';
				}
			} else {
				//注册成功，设置 Cookie，加密直接用 uc_authcode 函数，用户使用自己的函数
				setcookie('Example_auth', uc_authcode($uid."\t".$_POST['username'], 'ENCODE'), time() + 86400, $cookiepath);
				echo '注册成功'.$ucsynlogout.'<br><a href="/qsf_mvc/my/web/index/">继续</a>';
			}
		}

	}
	function pmlistAction() {
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		if(!empty($_COOKIE['Example_auth'])) {
			list($Example_uid, $Example_username) = explode("\t", uc_authcode($_COOKIE['Example_auth'], 'DECODE'));
		} else {
			$Example_uid = $Example_username = '';
		}
		/**
		 * 获取最新短消息
		 */
		$newpm = uc_pm_checknew($Example_uid);
		
		$timeoffset = 8;
		$ppp = 10;
		
		$phpself = '/qsf_mvc/my/web/pmlist';
		$act = !empty($_GET['act']) ? $_GET['act'] : '';
		
		$output = "
			<a href=\"$phpself/\">短消息</a>
			<a href=\"$phpself/filter/newpm/\">未读消息</a>
			<a href=\"$phpself/filter/announcepm/\">公共消息</a>
			<a href=\"$phpself/act/send/\">发送短消息</a>
			<a href=\"$phpself/act/viewblackls/\">黑名单</a>
			<hr>
		".print_r($newdata, 1);
		
		switch($act) {
			case '':
				$_GET['page'] =  max(1, intval($_GET['page']));
				$_GET['folder'] = !empty($_GET['folder']) ? $_GET['folder'] : 'inbox';
				$_GET['filter'] = !empty($_GET['filter']) ? $_GET['filter'] : '';
				
				$data = uc_pm_list($Example_uid, $_GET['page'], $ppp, $_GET['folder'], $_GET['filter'], 100);
				foreach($data['data'] as $pm) {
					if($_GET['filter'] != 'announcepm') {
						$output .= "<li>[$pm[msgfrom]]<a href=\"$phpself/act/view/touid/$pm[touid]/\">$pm[subject] (".gmdate('Y-m-d H:i:s', $pm['dateline'] + $timeoffset * 3600).")</a>";
						$pm['new'] && $output .= " New! ";
						$output .= "<br />$pm[message]";
					} else {
						$output .= "<li><a href=\"$phpself/act/view/pmid/$pm[pmid]/\">$pm[subject]</a>";
					}			
				}
				break;
			case 'view':
				$pmid = !empty($_GET['pmid']) ? $_GET['pmid'] : '';
				$data = uc_pm_view($Example_uid, $pmid, $_GET['touid']);
				foreach($data as $pm) {
					$output .= "<b>$pm[msgfrom] (".gmdate('Y-m-d H:i:s', $pm['dateline'] + $timeoffset * 3600)."):</b>";
					if($_GET['touid'] == $pm['msgfromid']) {
						$output .= "<a href=\"$phpself/act/addblackls/user/$pm[msgfrom]/\">[屏蔽]</a>";
					}
					$output .= "<br>$pm[message]<br><br>";
				}
				
				if(empty($_GET['pmid'])) {
					$output .= "
						<a href=\"$phpself/act/delete/uid/$_GET[touid]/\">删除</a>
						<form method=\"post\" action=\"$phpself/act/send/\">
						<input name=\"touid\" type=\"hidden\" value=\"$_GET[touid]\">
						<input name=\"subject\" value=\"\"><br>
						<textarea name=\"message\" cols=\"30\" rows=\"5\"></textarea>
						<input type=\"submit\">
						</form>
						";
				}
				break;
			case 'delete':
				if(uc_pm_deleteuser($Example_uid, array($_GET['uid']))) {
					$output .= "短消息已删除。";
				}
				break;
			case 'addblackls':
				$user = !empty($_GET['user']) ? $_GET['user'] : (!empty($_POST['user']) ? $_POST['user'] : '');
				if(uc_pm_blackls_add($Example_uid, $user)) {
					$output .= $_GET['user']." 已加入黑名单。";
				}
				break;
			case 'deleteblackls':
				if(uc_pm_blackls_delete($Example_uid, $_GET['user'])) {
					$output .= $_GET['user']." 已从黑名单中移除。";
				}
				break;
			case 'viewblackls':
				$data = explode(',', uc_pm_blackls_get($Example_uid));
				foreach($data as $ls) {
					$ls && $output .= "$ls <a href=\"$phpself/act/deleteblackls/user/$ls/\">[移除]</a>";
				}
				$output .= "
					<form method=\"post\" action=\"$phpself/act/addblackls/\">
					<input name=\"user\" value=\"\">
					<input type=\"submit\">
					</form>
					";
				break;
			case 'send':
				 if(!empty($_POST)) {
						if(!empty($_POST['touser'])) {
							$msgto = $_POST['touser'];
							$isusername = 1;
						} else {
							$msgto = $_POST['touid'];
							$isusername = 0;
						}
						if(uc_pm_send($Example_uid, $msgto, $_POST['subject'], $_POST['message'], 1, 0, $isusername)) {
							$output .= "短消息已发送";
						} else {
							$output .= "短消息发送失败，<a href=\"###\" onclick=\"history.back()\">返回</a>";
						}
					} else {
						$output .= "
							<form method=\"post\" action=\"$phpself/act/send/\">
							发送给:<input name=\"touser\" value=\"\"><br>
							标题:<input name=\"subject\" value=\"\"><br>
							内容:<textarea name=\"message\" cols=\"30\" rows=\"5\"></textarea>
							<input type=\"submit\">
							</form>
							";
					}
				break;
		}
		
		echo $output;	
	}
	function pmwinAction() {
		$this->initucAction();
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		//打开短消息中心的窗口
		uc_pm_location($Example_uid, $newpm);
		exit;
	}
	
	function friendAction() {
		$this->initucAction();
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		if(empty($_POST['submit'])) {
			$num = uc_friend_totalnum($Example_uid);
			echo '您有 '.$num.' 个好友';
			echo '<form method="post" action="/qsf_mvc/my/web/friend/">';
			$friendlist = uc_friend_ls($Example_uid, 1, 999, $num);
			if($friendlist) {
				foreach($friendlist as $friend) {
					echo '<input type="checkbox" name="delete[]" value="'.$friend['friendid'].'">';
					switch($friend['direction']) {
						case 1: echo '[关注]';break;
						case 3: echo '[好友]';break;
					}
					echo $friend['username'].':'.$friend['comment'].'<br>';
				}
			}
			echo '添加好友:<input name="newfriend"> 说明:<input name="newcomment"><br>';
			echo '<input name="submit" type="submit"> ';
			echo '</form>';
		} else {
			if(!empty($_POST['delete']) && is_array($_POST['delete'])) {
				uc_friend_delete($Example_uid, $_POST['delete']);
			}
			if($_POST['newfriend'] && $friendid = uc_get_user($_POST['newfriend'])) {
				uc_friend_add($Example_uid, $friendid[0], $_POST['newcomment']);
			}
			echo '好友资料已更新<br><a href="/qsf_mvc/my/web/friend/">继续</a>';
			exit;
		}
	}
	function avatarAction() {
		$this->initucAction();
		include APP_PATH.'./config.inc.php';
		include APP_PATH.'./uc_client/client.php';
		echo '
		<img src="'.UC_API.'/avatar.php?uid='.$Example_uid.'&size=big">
		<img src="'.UC_API.'/avatar.php?uid='.$Example_uid.'&size=middle">
		<img src="'.UC_API.'/avatar.php?uid='.$Example_uid.'&size=small">
		<br><br>'.uc_avatar($Example_uid);
	}
}